import deptApi from '@/api/deptApi'
import roleApi from '@/api/roleApi'
import userApi from '@/api/userApi'
import type { DeptItem } from '@/types/deptType'
import type { IAction, IModalProps } from '@/types/modal'
import type { RoleItem } from '@/types/roleType'
import type { UserItem } from '@/types/userType'
import { message } from '@/utils/AntdGlobal'
import storage from '@/utils/storage'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { Form, Input, Modal, Select, Upload, type GetProp, type UploadProps, Image, TreeSelect } from 'antd'
import { useEffect, useImperativeHandle, useState } from 'react'

const CreateUser = (props: IModalProps) => {
  const [visible, setVisible] = useState(false)
  const [action, setAction] = useState<IAction>('create')
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [roleList, setRoleList] = useState<RoleItem[]>([])
  const [img, setImg] = useState('')
  const [deptList, setDeptList] = useState<DeptItem[]>([])
  type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  const getRoleAllList = async () => {
    const res = await roleApi.getRoleAllList()
    setRoleList(res)
  }
  const getDeptList = async () => {
    const res = await deptApi.getDeptList()
    setDeptList(res)
  }
  const open = (type: IAction, data?: UserItem) => {
    setAction(type)
    if (type === 'edit' && data) {
      form.setFieldsValue(data)
      setImg(data.userImg)
    }
    setVisible(true)
  }
  const handleSubmit = async () => {
    await form.validateFields()
    let params = form.getFieldsValue(true)
    params = {
      ...params,
      userImg: img
    }
    if (action === 'create') {
      await userApi.userCreate(params)
      props.update()
      message.success('用户创建成功')
    }
    if (action === 'edit') {
      await userApi.userEdit(params)
      props.update()
      message.success('用户修改成功')
    }
    handleCancel()
  }
  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传png或jpg图片')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2M!')
    }
    return isJpgOrPng && isLt2M
  }
  const handleChange: UploadProps['onChange'] = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      setLoading(false)
      setImg(info.file.response.data.file)
    }
  }
  const handleCancel = () => {
    form.resetFields()
    setImg('')
    setVisible(false)
  }
  useEffect(() => {
    getRoleAllList()
    getDeptList()
  }, [])
  return (
    <Modal
      open={visible}
      title='新增用户'
      onOk={handleSubmit}
      onCancel={handleCancel}
      okText='确定'
      cancelText='取消'
      width={800}
    >
      <Form labelCol={{ span: 4 }} form={form} wrapperCol={{ span: 20 }}>
        <Form.Item
          label='用户名称'
          name='userName'
          rules={[
            { required: true, message: '请输入用户名称' },
            { min: 5, max: 12, message: '用户名称最小5个字符，最大12个字符' }
          ]}
        >
          <Input placeholder='请输入用户名称' />
        </Form.Item>
        <Form.Item
          label='邮箱'
          name='userEmail'
          rules={[
            { required: true, message: '请输入邮箱' },
            { pattern: /^\w+@mars.com$/, message: '邮箱必须以@mars.com结尾' }
          ]}
        >
          <Input placeholder='请输入邮箱:xxx@mars.com' disabled={action === 'edit'} />
        </Form.Item>
        <Form.Item
          label='手机号'
          name='mobile'
          rules={[{ pattern: /1[1-9]\d{9}/, message: '手机号必须为1开头的11位数字' }]}
        >
          <Input placeholder='请输入手机号' />
        </Form.Item>
        <Form.Item label='部门' name='deptId' rules={[{ required: true, message: '请选择部门' }]}>
          <TreeSelect
            placeholder='请选择部门'
            treeData={deptList}
            treeDefaultExpandAll
            fieldNames={{ label: 'deptName', value: '_id', children: 'children' }}
          ></TreeSelect>
        </Form.Item>
        <Form.Item label='岗位' name='job'>
          <Input placeholder='请输入岗位' />
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select
            placeholder='请选择状态'
            options={[
              { label: '在职', value: 1 },
              { label: '离职', value: 2 },
              { label: '试用期', value: 3 }
            ]}
          ></Select>
        </Form.Item>
        <Form.Item label='系统角色'>
          <Select
            placeholder='请选择系统角色'
            fieldNames={{ label: 'roleName', value: '_id' }}
            options={roleList}
          ></Select>
        </Form.Item>
        <Form.Item label='用户头像'>
          <Upload
            listType='picture-card'
            className='avatar-uploader'
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChange}
            action={`${import.meta.env.VITE_BASE_API}/users/upload`}
            headers={{ Authorization: `Bearer ${storage.get('token')}`, icode: import.meta.env.VITE_CODE }}
          >
            <div>
              {loading ? (
                <LoadingOutlined />
              ) : img ? (
                <Image src={img} />
              ) : (
                <div>
                  <PlusOutlined />
                  <div>Upload</div>
                </div>
              )}
            </div>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateUser
